package com.web.shiro;

import com.domain.system.Module;
import com.domain.system.User;
import com.service.system.ModuleService;
import com.service.system.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private ModuleService moduleService;
    @Autowired
    private UserService userService;

    @Override
    //自定义身份认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.传入的参数,需要强转为UsernamePasswordToken格式
        UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;

        //2.构造数据
        String email = upToken.getUsername();//根据用户输入,获取登录的用户名
        User user = userService.findByEmail(email);//查询数据库,获取User对象

        //3.返回AuthenticationInfo对象
        //SimpleAuthenticationInfo的3个参数(安全的数据(从数据库获取的User对象), 关键字段(数据库的密码), 自定义(realm的名字))
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), "MyRealm");
        return info;
    }

    @Override
    //自定义授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //1.传入的参数,需要的安全数据集合,此处应该是User对象,根据User对象获取拥有的模块
        User user = (User) principalCollection.getPrimaryPrincipal();

        //2.构造数据
        HashSet<String> perms = new HashSet<>();
        //遍历所有的模块,放入数据集合
        List<Module> modules = moduleService.findByUser(user);
        for (Module module : modules) {
            perms.add(module.getName());
        }

        //3.返回AuthorizationInfo对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(perms);
        return info;
    }

}
